//
//  DoorSystemDeviceListViewController.m
//  RONGAO
//
//  Created by ZhangYeKun on 2017/2/25.
//  Copyright © 2017年 wei wang. All rights reserved.
//

#import "DoorSystemDeviceListViewController.h"
#import "DSDeviceListTableViewCell.h"
#import "AddDoorSystemViewController.h"
#import "DoorSystemTabBarController.h"
#import "DoorSystemModel.h"
@interface DoorSystemDeviceListViewController ()<UITableViewDelegate,UITableViewDataSource,MyCameraDelegate>
{
    
    BOOL isRunOneTime;
    NSMutableArray *arrReConntFlag;
    BOOL isRecvSetArmResp;


}
/** tableView **/
@property(nonatomic,strong) UITableView *tableView;

/** 摄像头数组 **/
@property(nonatomic,strong) NSMutableArray *searchedData;

@end

@implementation DoorSystemDeviceListViewController



- (void)viewWillAppear:(BOOL)animated{

    [super viewWillAppear:animated];
    if ([AppDelegate globalDelegate].camera_list.count > 0) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"P2PPushUpdateDelegateNotification" object:self userInfo:nil];
    }
    
    
    
    [self.searchedData removeAllObjects];
    
    self.indexView = self.indexView;
    
    [[AppDelegate globalDelegate] loadDeviceFromDatabase];
    
    NSLog(@"=====================self.indexView:%ld",(long)self.indexView);
    [self.searchedData addObjectsFromArray:[[AppDelegate globalDelegate] loadDeviceFromDatabase:[NSString stringWithFormat:@"%ld",(long)self.indexView]]];
    
    
    
    for (MyCamera *camera in self.searchedData)
    {
        camera.delegate2 = self;
        NSLog(@"camera.uid:%@", camera.uid);
        
        NSString *device_uid = camera.uid;
        if (nil == device_uid || [device_uid isEqualToString:@""]) {
            device_uid = camera.deviceID;
        }
        
        for (MyCamera *camera in self.searchedData)

            
        {
            camera.delegate2 = self;
            NSLog(@"camera.uid:%@", camera.uid);
            
            NSString *device_uid = camera.uid;
            if (nil == device_uid || [device_uid isEqualToString:@""]) {
                device_uid = camera.deviceID;
            }
            
            if (device_uid)
            {
                [arrReConntFlag addObject:[NSMutableArray arrayWithObjects:[NSString stringWithString:device_uid], [NSNumber numberWithInt:0], nil]];
            }
        }

#if defined(P2PMENBOSHI) || defined(P2PBANDIANGOU) || defined(P2PXBROBOT) || defined(P2PWEXVS) //|| defined(P2PAUROCAM_WEX)
        [self armingSMsgAVIoctrlGet:camera];
#endif
#if defined(P2PMONITOR_LAMP) || defined(P2PVIDEODB)
        [self ledSMsgAVIoctrlGet:camera];
#endif
        
#if defined(P2PBANDIANGOU) || defined(P2PWEXVS)
        [self externalDeviceListSMsgAVIoctrlGet:camera];
        
        camera.isShowListView = NO;
#endif
    }
    
    
    [self restoreModeIndexToAllCam];

    [self.tableView reloadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setNavigationStyle];
    arrReConntFlag = [[NSMutableArray alloc] init];

    isRunOneTime = NO;

}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
}

- (void)viewDidDisappear:(BOOL)animated {

    [super viewDidDisappear:animated];
    [self.searchedData removeAllObjects];
#if defined(P2PNETCAM_HAIER)
    // disconnect device
    [self disLoopConnect];
#else
    //self.navigationController.navigationBar.translucent = NO;
#endif
    for( NSMutableArray* store in arrReConntFlag ) {
        if( [store count] == 3 ) {
            NSTimer* timer = [store objectAtIndex:2];
            [timer invalidate];
            //[timer release];
        }
    }
    [arrReConntFlag removeAllObjects];


}


- (void)restoreModeIndexToAllCam {
    
    for (int i=0; i<self.searchedData.count; i++) {
        MyCamera *cam = (MyCamera *)[self.searchedData objectAtIndex:i];
        
        [self restoreModeIndexToCam:cam];
    }
}
- (void)restoreModeIndexToCam:(MyCamera *)cam {
    
    cam.newModeValue1 = cam.orgModeValue1;
    
}

#if defined(P2PMONITOR_LAMP) || defined(P2PVIDEODB)
- (void)ledSMsgAVIoctrlGet:(MyCamera *)camera
{
    NSLog(@"armingSMsgAVIoctrlGet");
    SMsgAVIoctrlThirdpartReq *structArming = (SMsgAVIoctrlThirdpartReq *)malloc(sizeof(SMsgAVIoctrlThirdpartReq));
    memset(structArming, 0, sizeof(SMsgAVIoctrlThirdpartReq));
    
    structArming->command_types_ = THIRD_PART_GET_LED_STATUS;
    
    [camera sendIOCtrlToChannel:0
                           Type:IOTYPE_USER_IPCAM_THIRDPART_SETTING_REQ
                           Data:(char *)structArming
                       DataSize:sizeof(SMsgAVIoctrlThirdpartReq)];
    free(structArming);
}

- (void)ledSMsgAVIoctrlSet:(MyCamera *)camera
{
    SMsgAVIoctrlThirdpartReq *s = (SMsgAVIoctrlThirdpartReq *)malloc(sizeof(SMsgAVIoctrlThirdpartReq));
    memset(s, 0, sizeof(SMsgAVIoctrlThirdpartReq));
    
    s->command_types_ = THIRD_PART_SET_LED_STATUS;
    s->value1_ = (int)camera.newContrlValue1;
    
    [camera sendIOCtrlToChannel:0
                           Type:IOTYPE_USER_IPCAM_THIRDPART_SETTING_REQ
                           Data:(char *)s
                       DataSize:sizeof(SMsgAVIoctrlThirdpartReq)];
    
    free(s);
    
}
#endif




#if defined(P2PMENBOSHI) || defined(P2PBANDIANGOU) || defined(P2PXBROBOT) || defined(P2PWEXVS) || defined(P2PVIDEODB) || defined(P2PAUROCAM_WEX)
#pragma mark - get set arming or disarming
- (void)armingSMsgAVIoctrlGet:(MyCamera *)camera
{
    NSLog(@"armingSMsgAVIoctrlGet");
    SMsgAVIoctrlThirdpartReq *structArming = (SMsgAVIoctrlThirdpartReq *)malloc(sizeof(SMsgAVIoctrlThirdpartReq));
    memset(structArming, 0, sizeof(SMsgAVIoctrlThirdpartReq));
    
    structArming->command_types_ = THIRD_PART_GET_ALARMED_STATUS;
    
    [camera sendIOCtrlToChannel:0
                           Type:IOTYPE_USER_IPCAM_THIRDPART_SETTING_REQ
                           Data:(char *)structArming
                       DataSize:sizeof(SMsgAVIoctrlThirdpartReq)];
    free(structArming);
}

#endif

- (void)externalDeviceListSMsgAVIoctrlGet:(MyCamera *)camera
{
    NSLog(@"externalDeviceListSMsgAVIoctrlGet");
    SmsgAVIoctrlEditAllDevicesReq *s = (SmsgAVIoctrlEditAllDevicesReq *)malloc(sizeof(SmsgAVIoctrlEditAllDevicesReq));
    memset(s, 0, sizeof(SmsgAVIoctrlEditAllDevicesReq));
    
    s->type = EDIT_433_LIST_TYPE_GET_ALARM_INFO ;
    
    [camera sendIOCtrlToChannel:0
                           Type:IOTYPE_USER_IPCAM_433_EDITDIVICES_LIST_REQ
                           Data:(char *)s
                       DataSize:sizeof(SmsgAVIoctrlEditAllDevicesReq)];
    free(s);
}


#pragma mark - Application's Documents directory

/**
 Returns the URL to the application's Documents directory.
 */
- (NSURL *)applicationDocumentsDirectory
{
    return [[[NSFileManager defaultManager]
             URLsForDirectory:NSDocumentDirectory
             inDomains:NSUserDomainMask] lastObject];
}

- (NSString *) pathForDocumentsResource:(NSString *) relativePath {
    
    static NSString* documentsPath = nil;
    
    if (nil == documentsPath) {
        
        NSArray* dirs = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        documentsPath = [dirs objectAtIndex:0];
    }
    
    return [documentsPath stringByAppendingPathComponent:relativePath];
}


#pragma mark - MyCameraDelegate Methods
- (void)camera:(MyCamera *)camera _didChangeSessionStatus:(NSInteger)status
{
    if (camera.sessionState == CONNECTION_STATE_TIMEOUT) {
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
            
            [camera disconnect];
            
        });
    }
    [self.tableView reloadData];

    NSString *device_uid = camera.uid;
    
    if (nil == device_uid || [device_uid isEqualToString:@""]) {
        device_uid = camera.deviceID;
    }
    
    if( camera.sessionState == CONNECTION_STATE_DISCONNECTED ||
       camera.sessionState == CONNECTION_STATE_UNKNOWN_DEVICE ||
       camera.sessionState == CONNECTION_STATE_TIMEOUT ||
       camera.sessionState == CONNECTION_STATE_UNSUPPORTED ||
       camera.sessionState == CONNECTION_STATE_CONNECT_FAILED ) {
        
        NSMutableArray* storeToSetTimer = nil;
        int nReConntFlag = -1;
        for( NSMutableArray* store in arrReConntFlag ) {
            
            
            NSString* uidInStore = [store objectAtIndex:0];
            if( NSOrderedSame == [device_uid compare:uidInStore options:NSCaseInsensitiveSearch] ) {
                NSNumber* num = [store objectAtIndex:1];
                nReConntFlag = [num intValue];
                [store replaceObjectAtIndex:1 withObject:[NSNumber numberWithInt:++nReConntFlag]];
                storeToSetTimer = store;
                break;
            }
        }
        if( nReConntFlag == 1 ) {
            NSLog( @"Camera UID:%@ will re-connect in 30sec...", device_uid );
            [storeToSetTimer addObject:[NSTimer scheduledTimerWithTimeInterval:30.0 target:self selector:@selector(ReConnectAfter30Sec:) userInfo:[NSArray arrayWithObjects:[NSString stringWithString:device_uid], [NSValue valueWithPointer:(__bridge const void * _Nullable)(camera)], nil] repeats:NO] ];
        }
        else {
            NSLog( @"Camera UID:%@ give up re-connect nReConntFlag:%d", device_uid, nReConntFlag );
        }
    }
    else if( camera.sessionState == CONNECTION_STATE_CONNECTED ) {
        for( NSMutableArray* store in arrReConntFlag ) {
            NSString* uidInStore = [store objectAtIndex:0];
            if( NSOrderedSame == [device_uid compare:uidInStore options:NSCaseInsensitiveSearch] ) {
                [store replaceObjectAtIndex:1 withObject:[NSNumber numberWithInt:0]];
                NSLog( @"Camera UID:%@ reset re-connect flag as -0-", device_uid );
                break;
            }
        }
        
        
    }

    
    
}

- (void)ReConnectAfter30Sec:(NSTimer*)theTimer
{
    
    NSArray* arrParam = (NSArray*)theTimer.userInfo;
    NSString* strUid = [arrParam objectAtIndex:0];
    MyCamera* camera = (MyCamera*)[(NSValue*)[arrParam objectAtIndex:1] pointerValue];
    
    BOOL isGo = NO;
#if defined(P2PWEXVS)
    
    if ([camera.deviceType isEqualToString:DEV_TYPE_ADD_3_SAFEBOX]) {
        
        
        isGo = NO;
    } else {
        isGo = YES;
    }
#else
    isGo = YES;
    
#endif
    
    if (isGo) {
        
        
        BOOL bIsValid_Camera = FALSE;
        for( NSMutableArray* store in arrReConntFlag ) {
            NSString* uidInStore = [store objectAtIndex:0];
            if( NSOrderedSame == [strUid compare:uidInStore options:NSCaseInsensitiveSearch] ) {
                bIsValid_Camera = TRUE;
                if( [store count] == 3 ) {
                    NSTimer* timer = [store objectAtIndex:2];
                    [timer invalidate];
                    //				[timer release];
                    [store removeObjectAtIndex:2];
                    break;
                }
            }
        }
        if( bIsValid_Camera ) {
            NSLog( @"ReConnectAfter30Sec camera.uid:%@ camera connect and start!", camera.uid );
            
            [camera connect:camera.uid];
            [camera start:0];
        }
        else {
            NSLog( @"ReConnectAfter30Sec with deallocated instance!!! camera.uid:%@", camera.uid );
        }
        
    }
}



- (void)camera:(MyCamera *)camera _didChangeChannelStatus:(NSInteger)channel ChannelStatus:(NSInteger)status
{
    if (status == CONNECTION_STATE_TIMEOUT) {
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
            
            [camera stop:channel];
            
            usleep(500 * 1000);
            
            [camera disconnect];
        });
    }
    [self.tableView reloadData];
}


- (void)camera:(MyCamera *)camera_ _didReceiveIOCtrlWithType:(NSInteger)type Data:(const char *)data DataSize:(NSInteger)size {
    
    NSLog(@"CLFVC _didReceiveIOCtrlWithType type:%ld(%lx)", (long)type, (long)type);
    
#if defined(DEV_LIST_CONTRL)|| defined(P2PVIDEODB)
    if (type == IOTYPE_USER_IPCAM_THIRDPART_SETTING_RESP) {
        SMsgAVIoctrlThirdpartResp *s = (SMsgAVIoctrlThirdpartResp*)data;
        NSLog(@"IOTYPE_USER_IPCAM_THIRDPART_SETTING_RESP s->command_types_:%d, s->result_:%d, s->value_:%d",
              s->command_types_, s->result_, s->value_);
        if (THIRD_PART_GET_LED_STATUS == s->command_types_) {
            //[[iToast makeText:NSLocalizedString(@"IR Correct Success", @"")]show];
            
#if defined(P2PVIDEODB)
            
            
            if (s->result_ < 0) {
            } else {
                camera_.orgContrlValue1 = s->value_;
                camera_.newContrlValue1 = s->value_;
                
                [self.tableView reloadData];
            }
#else
            camera_.orgContrlValue1 = s->result_;
            camera_.newContrlValue1 = s->result_;
            
            [self.tableView reloadData];
#endif
            
            
#if 0
            if (0 == s->result_) {
                NSLog(@"camera_.orgContrlValue1:%ld, camera_.newContrlValue1:%ld",
                      (long)camera_.orgContrlValue1, (long)camera_.newContrlValue1);
                //if (camera_.orgArming < 0)
                {
                    camera_.orgContrlValue1 = s->value_;
                    camera_.newContrlValue1 = s->value_;
                    
                    [self.tableView reloadData];
                    
                }
            } else {
                /*
                 dispatch_queue_t queue = dispatch_queue_create("led_get_status", NULL);
                 dispatch_async(queue, ^{
                 
                 usleep(3*1000*1000);
                 
                 [self ledSMsgAVIoctrlGet:camera_];
                 });
                 
                 dispatch_release(queue);
                 */
            }
#endif
            
        } else if (THIRD_PART_SET_LED_STATUS == s->command_types_) {
            //[[iToast makeText:NSLocalizedString(@"IR Correct Fail", @"")]show];
            NSLog(@"camera_.newContrlValue1:%ld", (long)camera_.newContrlValue1);
            if (0 == s->result_) {
                camera_.orgContrlValue1 = camera_.newContrlValue1;
                
                [self.tableView reloadData];
                
            } else {
                
                camera_.orgContrlValue1 = (camera_.newContrlValue1 == 1) ? 0 : 1;
                
                [self.tableView reloadData];
            }
            
        }
    }
    
#endif
    
#if defined(P2PMENBOSHI) || defined(P2PBANDIANGOU) || defined(P2PXBROBOT) || defined(P2PWEXVS)  || defined(P2PAUROCAM_WEX) //|| defined(P2PVIDEODB)
    if (type == IOTYPE_USER_IPCAM_THIRDPART_SETTING_RESP) {
        SMsgAVIoctrlThirdpartResp *s = (SMsgAVIoctrlThirdpartResp*)data;
        NSLog(@"IOTYPE_USER_IPCAM_THIRDPART_SETTING_RESP s->command_types_:%d, s->result_:%d, s->value_:%d",
              s->command_types_, s->result_, s->value_);
        if (THIRD_PART_GET_ALARMED_STATUS == s->command_types_) {
            //[[iToast makeText:NSLocalizedString(@"IR Correct Success", @"")]show];
            
            if (0 == s->result_) {
                NSLog(@"camera_.orgArming:%ld, camera_.newArming:%ld",
                      (long)camera_.orgArming, (long)camera_.newArming);
                //if (camera_.orgArming < 0)
                {
                    camera_.orgArming = s->value_;
                    camera_.newArming = s->value_;
                    
                    [self.tableView reloadData];
                    
                }
            } else {
            }
            
            
        } else if (THIRD_PART_SET_ALARMED_STATUS == s->command_types_) {
            //[[iToast makeText:NSLocalizedString(@"IR Correct Fail", @"")]show];
            
            if (0 == s->result_) {
                camera_.orgArming = s->value_;
                NSString *arm;
                if (camera_.orgArming) {
                    arm = NSLocalizedString(@"Arming", @"");
                } else {
                    arm = NSLocalizedString(@"Disarming", @"");
                }
                NSString *showStr = [NSString stringWithFormat:@"%@  %@", camera_.name, arm];
                
//                [[iToast makeText:showStr]show];
                
                [self.tableView reloadData];
                
            } else {
                NSString *arm;
                if (camera_.newArming) {
                    arm = NSLocalizedString(@"Arming", @"");
                } else {
                    arm = NSLocalizedString(@"Disarming", @"");
                }
                NSString *showStr = [NSString stringWithFormat:@"%@  %@ Fail", camera_.name, arm];
                
//                [[iToast makeText:showStr]show];
                
                [self.tableView reloadData];
                
            }
            
        }
    }
    
#endif
    
    if (type == IOTYPE_USER_IPCAM_EVENT_REPORT) {
        NSLog(@"IOTYPE_USER_IPCAM_EVENT_REPORT camera_.uid:%@", camera_.uid);
        
        SMsgAVIoctrlEvent *s = (SMsgAVIoctrlEvent *)data;
        
        NSLog(@"IOTYPE_USER_IPCAM_EVENT_REPORT s->event:%d", s->event);
        NSLog(@"IOTYPE_USER_IPCAM_EVENT_REPORT s->time:%d", s->time);
        
        NSLog(@"IOTYPE_USER_IPCAM_EVENT_REPORT s->stTime.hour:%d", s->stTime.hour);
        NSLog(@"IOTYPE_USER_IPCAM_EVENT_REPORT s->stTime.minute:%d", s->stTime.minute);
        NSLog(@"IOTYPE_USER_IPCAM_EVENT_REPORT s->stTime.second:%d", s->stTime.second);
        
        
        
    } else if(type == IOTYPE_USER_IPCAM_433_EDITDIVICES_LIST_RESP) {
        SmsgAVIoctrlEditAllDevicesResp *s = (SmsgAVIoctrlEditAllDevicesResp*)data;
        NSLog(@"CameraListForLiveViewController IOTYPE_USER_IPCAM_433_EDITDIVICES_LIST_RESP s->result_:%d, s->type:%d, s->alarm_type:%d, s->devices_.num_:%d", s->result, s->type, s->alarm_type, s->devices_.num_);
        
        isRecvSetArmResp = YES;
        
        if (0 == s->result) {
            
            NSLog(@"begin camera_.orgModeValue1:%ld, camera_.newModeValue1:%ld", (long)camera_.orgModeValue1, (long)camera_.newModeValue1);
            camera_.orgModeValue1 = camera_.newModeValue1;
            
            if (EDIT_433_LIST_TYPE_GET_ALARM_INFO == s->type) {
            } else if (EDIT_433_LIST_TYPE_SET_ALARM_TYPE == s->type) {
            } else if (EDIT_433_LIST_TYPE_SET_CLOSE_TYPE == s->type) {
            } else if (EDIT_433_LIST_TYPE_SAVE_USER_DEFINED_TYPE == s->type) {
            }
        }
        
        [self.tableView reloadData];
    }
    
}


- (void)externalDeviceListSMsgAVIoctrlSet:(MyCamera *)camera ctrlType:(NSInteger)type armType:(NSInteger)arm_type
{
    NSLog(@"externalDeviceListSMsgAVIoctrlSet");
    
    isRecvSetArmResp = NO;
    
    SmsgAVIoctrlEditAllDevicesReq *s = (SmsgAVIoctrlEditAllDevicesReq *)malloc(sizeof(SmsgAVIoctrlEditAllDevicesReq));
    memset(s, 0, sizeof(SmsgAVIoctrlEditAllDevicesReq));
    
    s->type = (int)type;
    
    s->alarm_type = (int)arm_type;
    
    ////int     alarm_type;//0-disable, 1-onekey-alarm , 2-home-alarm, 3-store-alarm, 4-use-defined, 5-invalid
    
    switch (s->alarm_type) {
        case BDG_MODE_DEFAULT_INDEX:
            break;
            
        case BDG_MODE_ONEKEY_INDEX:
            break;
            
        case BDG_MODE_HOME_INDEX:
            break;
            
        case BDG_MODE_STORE_INDEX:
            break;
            
        case BDG_MODE_USER_INDEX:
        {
            
        }
            break;
            
        case BDG_MODE_DEVICE_INDEX:
        {
            
        }
            break;
            
        default:
        {
        }
            break;
            
    }
    
    NSInteger num = camera.externalDeviceListArr.count;
    NSLog(@"num=%ld", (long)num);
    
    s->devices_.num_ = (int)num;
    
    for (int i=0; i<camera.externalDeviceListArr.count; i++) {
     
        /*
        Alarm433Device *dev = (Alarm433Device *)[camera.externalDeviceListArr objectAtIndex:i];
        //dev.key = [NSString stringWithUTF8String:s->devices_.devices_array_[i].key_];
        memcpy(s->devices_.devices_array_[i].key_, dev.key.UTF8String, sizeof(s->devices_.devices_array_[i].key_));
        
        //dev.alias = [NSString stringWithUTF8String:s->devices_.devices_array_[i].aliase_];
        memcpy(s->devices_.devices_array_[i].aliase_, dev.alias.UTF8String, sizeof(s->devices_.devices_array_[i].aliase_));
        
        s->devices_.devices_array_[i].device_type_ = dev.device_type;
        s->devices_.devices_array_[i].device_vender_ = dev.device_vender;
        
#if defined(BUILD_FOR_GANSU_CAM)
        s->devices_.devices_array_[i].device_alarmed = dev.new_device_alarmed;
        s->devices_.devices_array_[i].alarm_ptz_preset = dev.new_alarm_ptz_preset;
        s->devices_.devices_array_[i].device_closed = dev.new_device_closed;
#endif
        
        dev.device_alarmed = dev.new_device_alarmed;
        dev.alarm_ptz_preset = dev.new_alarm_ptz_preset;
        dev.device_closed = dev.new_device_closed;
        
        NSLog(@"i:%d dev.alias:%@, dev.key:%@", i, dev.alias, dev.key);
        NSLog(@"dev.device_type:%ld, dev.device_vender:%ld, dev.device_alarmed:%ld, dev.alarm_ptz_preset:%ld, dev.device_closed:%ld", (long)dev.device_type, (long)dev.device_vender, (long)dev.device_alarmed, (long)dev.alarm_ptz_preset, (long)dev.device_closed);
         */
    }
    
    
    NSLog(@"externalDeviceListSMsgAVIoctrlSet IOTYPE_USER_IPCAM_433_EDITDIVICES_LIST_REQ s->type:%d, s->alarm_type:%d, s->devices_.num_:%d", s->type, s->alarm_type, s->devices_.num_);
    
    
    [camera sendIOCtrlToChannel:0
                           Type:IOTYPE_USER_IPCAM_433_EDITDIVICES_LIST_REQ
                           Data:(char *)s
                       DataSize:sizeof(SmsgAVIoctrlEditAllDevicesReq)];
    free(s);
}



- (void)externalDeviceListSetTask {
    
    for (int i=0; i<100; i++) {
        if (isRecvSetArmResp) {
            break;
        }
        NSLog(@"externalDeviceListSetTask i=%d", i);
        usleep(100*1000);
    }
    
}








#pragma mark - --------------------------touch event--------------------------
- (void)onRightButtonClick:(id)sender{
    
    AddDoorSystemViewController *addDSVC = [[AddDoorSystemViewController alloc]init];
    
    addDSVC.indexView = self.indexView;
    self.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:addDSVC animated:YES];
    
}

#pragma mark - --------------------------UITableView dataSource--------------------------

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return self.searchedData.count;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 1;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    Camera *camera = self.searchedData[indexPath.section];

    DSDeviceListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kDSDeviceListIdentifier];
        
    if (cell == nil) {
        
        cell = [[DSDeviceListTableViewCell alloc]init];
        
    }
    
    NSString *imgFullName = [self pathForDocumentsResource:[NSString stringWithFormat:@"%@.jpg",camera.uid]];
    
    BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:imgFullName];
    
    cell.videoImageView.image = fileExists ? [UIImage imageWithContentsOfFile:imgFullName] : [UIImage imageNamed:@"bg_31"];

    [cell.nicknameButton setTitle:camera.name forState:UIControlStateNormal];
    
    #pragma mark - --------------------------摄像头连接状态--------------------------
    
    NSLog(@"camera.sessionState:%ld, [camera getConnectionStateOfChannel:0]:%d", (long)camera.sessionState, [camera getConnectionStateOfChannel:0]);
    
    if (camera.sessionState == CONNECTION_STATE_CONNECTING) {
        [cell.onlineButton setTitle:@"连接中..." forState:UIControlStateNormal];
        NSLog(@"%@ connecting CLFLVC 0", camera.uid);
    }
    else if (camera.sessionState == CONNECTION_STATE_DISCONNECTED) {
        
        [cell.onlineButton setTitle:@"离线" forState:UIControlStateNormal];
        cell.onlineButton.selected = NO;

        NSLog(@"%@ off line CLFLVC 0", camera.uid);
    }
    else if (camera.sessionState == CONNECTION_STATE_UNKNOWN_DEVICE) {
        [cell.onlineButton setTitle:@"未知设备" forState:UIControlStateNormal];
        NSLog(@"%@ unknown device CLFLVC 0", camera.uid);
    }
    else if (camera.sessionState == CONNECTION_STATE_TIMEOUT) {
        [cell.onlineButton setTitle:@"超时" forState:UIControlStateNormal];
        NSLog(@"%@ timeout CLFLVC 0", camera.uid);
    }
    else if (camera.sessionState == CONNECTION_STATE_UNSUPPORTED) {
        [cell.onlineButton setTitle:@"不支持" forState:UIControlStateNormal];
        NSLog(@"%@ unsupported CLFLVC 0", camera.uid);
    }
    else if (camera.sessionState == CONNECTION_STATE_CONNECT_FAILED) {
        [cell.onlineButton setTitle:@"连接失败" forState:UIControlStateNormal];
        NSLog(@"%@ connected failed CLFLVC 0", camera.uid);
    }

    
    if (camera.sessionState == CONNECTION_STATE_CONNECTED && [camera getConnectionStateOfChannel:0] == CONNECTION_STATE_CONNECTED) {
        [cell.onlineButton setTitle:@"在线" forState:UIControlStateNormal];
        cell.onlineButton.selected = YES;
        NSLog(@"%@ online CLFLVC 1", camera.uid);
    }
    else if (camera.sessionState == CONNECTION_STATE_CONNECTED && [camera getConnectionStateOfChannel:0] == CONNECTION_STATE_CONNECTING) {
        [cell.onlineButton setTitle:@"连接中..." forState:UIControlStateNormal];
        NSLog(@"%@ connecting CLFLVC 1", camera.uid);
    }
    else if (camera.sessionState == CONNECTION_STATE_CONNECTED && [camera getConnectionStateOfChannel:0] == CONNECTION_STATE_DISCONNECTED)
    {
        [cell.onlineButton setTitle:@"离线" forState:UIControlStateNormal];
        NSLog(@"%@ off line CLFLVC 1", camera.uid);
        cell.onlineButton.selected = NO;

        //[self isOverToReConnect:camera.uid cameraStatus:1];
    }
    else if (camera.sessionState == CONNECTION_STATE_CONNECTED && [camera getConnectionStateOfChannel:0] == CONNECTION_STATE_UNKNOWN_DEVICE) {
        [cell.onlineButton setTitle:@"未知设备" forState:UIControlStateNormal];
        NSLog(@"%@ unknown device CLFLVC 1", camera.uid);
    }
    else if (camera.sessionState == CONNECTION_STATE_CONNECTED && [camera getConnectionStateOfChannel:0] == CONNECTION_STATE_WRONG_PASSWORD) {
        [cell.onlineButton setTitle:@"密码错误" forState:UIControlStateNormal];
        NSLog(@"%@ wrong password CLFLVC 1", camera.uid);
    }
    else if (camera.sessionState == CONNECTION_STATE_CONNECTED && [camera getConnectionStateOfChannel:0] == CONNECTION_STATE_TIMEOUT) {
        [cell.onlineButton setTitle:@"超时" forState:UIControlStateNormal];
        NSLog(@"%@ timeout CLFLVC 1", camera.uid);
    }
    else if (camera.sessionState == CONNECTION_STATE_CONNECTED && [camera getConnectionStateOfChannel:0] == CONNECTION_STATE_UNSUPPORTED) {
        [cell.onlineButton setTitle:@"不支持" forState:UIControlStateNormal];
        NSLog(@"%@ unsupported CLFLVC 1", camera.uid);
    }
    else if (camera.sessionState == CONNECTION_STATE_CONNECTED && [camera getConnectionStateOfChannel:0] == CONNECTION_STATE_NONE) {
        [cell.onlineButton setTitle:@"连接中..." forState:UIControlStateNormal];
        NSLog(@"%@ wait for connecting CLFLVC 1", camera.uid);
    }
    
    
    if (camera.sessionState == CONNECTION_STATE_DISCONNECTED ||
        [camera getConnectionStateOfChannel:0] == CONNECTION_STATE_CONNECTED ||
        [camera getConnectionStateOfChannel:0] == CONNECTION_STATE_WRONG_PASSWORD ||
        [camera getConnectionStateOfChannel:0] == CONNECTION_STATE_TIMEOUT ||
        [camera getConnectionStateOfChannel:0] == CONNECTION_STATE_CONNECT_FAILED ) {
        
        //[self isOverToReConnect:camera.uid cameraStatus:1];
    }

    
#pragma mark - --------------------------load camera backgroundimage--------------------------
    /* load camera backgroundImage */

    
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    
    
    return cell;
    
}



#pragma mark - --------------------------UITableView delegate--------------------------

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 240.f;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return 10.f;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
#pragma mark - --------------------------摄像头连接状态--------------------------
    
    MyCamera *camera = self.searchedData[indexPath.section];
    
    [AppDelegate globalDelegate].cameraModel = camera;
    
    [self getIsRecvAudioFormat:camera];
    DoorSystemTabBarController *vc = [[DoorSystemTabBarController alloc] init];
    
    [self.navigationController pushViewController:vc animated:YES];
    
    
}

- (BOOL)getIsRecvAudioFormat:(MyCamera *)cam {
    BOOL isRecvAudioFormat = NO;
    
#if defined(AUDIO_TO_SUPPORT)
    if (cam) {
        if (cam.sessionState == CONNECTION_STATE_CONNECTED) {
            
            //if ([camera getConnectionStateOfChannel:0] == CONNECTION_STATE_CONNECTED)
            
            isRecvAudioFormat = cam.isRecvAudioFormat;
            
            if (isRecvAudioFormat) {
                
            } else {
                NSLog(@"IOTYPE_USER_IPCAM_GETAUDIOOUTFORMAT_REQ");
                SMsgAVIoctrlGetAudioOutFormatReq *s = (SMsgAVIoctrlGetAudioOutFormatReq *)malloc(sizeof(SMsgAVIoctrlGetAudioOutFormatReq));
                s->channel = 0;
                [cam sendIOCtrlToChannel:0 Type:IOTYPE_USER_IPCAM_GETAUDIOOUTFORMAT_REQ Data:(char *)s DataSize:sizeof(SMsgAVIoctrlGetAudioOutFormatReq)];
                free(s);
            }
        }
    }
    
#endif
    NSLog(@"CameraListForLiveViewController isRecvAudioFormat:%d", isRecvAudioFormat);
    
    
    return isRecvAudioFormat;
}





- (UITableView *)tableView{
    
    if (!_tableView) {
        
        __weak UIView *superView = self.view;
        _tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        [superView addSubview:_tableView];
        //        _tableView.separatorStyle = UITableViewCellSelectionStyleNone;//隐藏tableView的分割线
        //        _tableView.scrollEnabled = NO;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        
    }
    
    return _tableView;
    
}

- (void)setNavigationStyle{
    
    [self setLeftButtonImage:[UIImage imageNamed:@"icon_back_nor"]];
    [self setNavigationTitle:@"门载智能系统" titleColor:[UIColor colorWithRed:210/255.0 green:177/255.0 blue:104/255.0 alpha:1]];
    [self setRightButtonImage:[UIImage imageNamed:@"icon_add_nor"]];
    
}


- (void)masLayoutSubview{
    
    __weak UIView *superView = self.view;
    [self.tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
       
        make.edges.mas_equalTo(superView);
        
    }];
    
}

- (NSMutableArray *)searchedData{
    
    if (!_searchedData) {
        
        _searchedData = [NSMutableArray array];
    }
    return _searchedData;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}



@end
